package cn.ddiancan.auth.service.converter;

import org.apache.http.HttpStatus;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.http.converter.OAuth2ErrorHttpMessageConverter;

public class XddOAuth2ErrorHttpMessageConverter extends OAuth2ErrorHttpMessageConverter {

    @Override
    protected void writeInternal(OAuth2Error oauth2Error, HttpOutputMessage outputMessage)
        throws HttpMessageNotWritableException {
        if (outputMessage instanceof ServletServerHttpResponse servletResponse) {
            // 设置响应头
            servletResponse.setStatusCode(HttpStatusCode.valueOf(HttpStatus.SC_UNAUTHORIZED));
            servletResponse.getHeaders().set("Content-Type", "application/json;charset=UTF-8");
            servletResponse.getHeaders().set(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate");
            servletResponse.getHeaders().set(HttpHeaders.SET_COOKIE,
                "JSESSIONID=; Path=/; HttpOnly ; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT");
            super.writeInternal(oauth2Error, servletResponse);
        }
    }
}
